<template>
  <div class="desktop-content">
    <div class="desktop-column-box">
      <div class="pagingAndSearch-box">
        <div class="paging-list-box">
          <div
            class="paging-list-item"
            :class="{ 'paging-list-item-active': pageQuery.category_id === item.id }"
            v-for="item in oneCategories"
            :key="item.id"
            @click="onSelectOneCategory(item)"
          >
            <div class="name">{{ item.name }}</div>
          </div>
          <div class="paging-list-btn">
            <img
              class="left-btn"
              @click.stop="oneCatePreviousPage"
              src="@/assets/images/home/page-left-icon.png"
              :style="{ cursor: oneCategoryPage === 1 ? 'not-allowed' : 'pointer' }"
              alt=""
            />
            <img
              class="right-btn"
              @click.stop="oneCateNextPage"
              src="@/assets/images/home/page-right-icon.png"
              :style="{
                cursor: oneCategoryPage >= foodOneCategoryLastPage ? 'not-allowed' : 'pointer'
              }"
              alt=""
            />
          </div>
        </div>
        <div class="search-box">
          <div class="content1">
            <img src="@/assets/images/home/sousuo-icon.png" alt="" />
            <input
              v-model.trim="pageQuery.keywords"
              type="text"
              @input="onSearch"
              placeholder="搜索菜品"
            />
          </div>
        </div>
      </div>

      <div class="tag-select-box" v-if="twoCategories.length">
        <div class="tag-btn-list">
          <div
            class="tag-btn-item"
            :class="{ 'tag-btn-item-active': pageQuery.category_id === item.id }"
            v-for="item in twoCategories"
            :key="item.id"
            @click="onSelectTwoCategory(item)"
          >
            {{ item.name }}
          </div>
        </div>
        <div class="tag-paging-list-btn">
          <img
            class="left-btn"
            @click="twoCatePreviousPage"
            src="@/assets/images/home/page-left-icon.png"
            :style="{ cursor: twoCategoryPage === 1 ? 'not-allowed' : 'pointer' }"
            alt=""
          />
          <img
            class="right-btn"
            @click="twoCateNextPage"
            :style="{
              cursor: twoCategoryPage >= foodTwoCategoryLastPage ? 'not-allowed' : 'pointer'
            }"
            src="@/assets/images/home/page-right-icon.png"
            alt=""
          />
        </div>
      </div>
    </div>

    <div
      :class="twoCategories.length ? 'desktop-scroll-list-two' : 'desktop-scroll-list'"
      v-loading="listLoading"
    >
      <div class="scroll-list-item-content" v-if="filteredFoods && filteredFoods.length">
        <div
          class="scroll-list-item"
          v-for="food in filteredFoods"
          :key="food.id"
          @click="emitSelectFood(food)"
        >
          <img
            class="image"
            v-if="food?.images && food.images.length && food.images[0]?.file?.preview_url"
            :src="food.images[0].file.preview_url"
            alt=""
          />
          <div class="not-good-image" v-else>
            <img class="image" src="@/assets/images/home/not-goodimage.png" alt="" />
          </div>
          <div class="desc-box">
            <div class="name">{{ food.name }}</div>
            <!-- <div class="vip-money" v-if="food?.skuList?.[0]?.member_price">
              ￥{{ food.skuList[0].member_price }}/份
            </div> -->
            <div class="money">￥{{ food.skuList?.[0]?.price }}/份</div>
            <div class="count" v-if="food?.skuList?.[0]?.num !== undefined">
              剩余：{{ food.skuList[0].num }}
            </div>
          </div>
          <div class="positon-soldOut-box" v-if="food.num === 0">
            <img class="image" src="@/assets/images/home/yishouqing-icon.png" alt="" />
          </div>
        </div>
      </div>
      <div class="no-data-box" v-else>
        <NotData desc="暂无菜品数据" />
      </div>
    </div>

    <div class="desktop-actions-btn-box">
      <div class="count-desc">
        <span v-if="filteredFoods && filteredFoods.length">共{{ filteredFoods.length }}项</span>
      </div>
      <div class="btn-list">
        <div class="btn-item" @click="emitAction('cookbook')">菜谱</div>
        <div class="btn-item" @click="emitBack">返回</div>
      </div>
    </div>

    <!-- 菜谱弹框 -->
    <FoodCookBookDialog 
      :visible="showCookBookDialog" 
      @update:visible="showCookBookDialog = $event"
      @confirm="handleCookBookConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import NotData from '@/components/NotData/Index.vue'
import FoodCookBookDialog from './components/FoodCookBookDialog/Index.vue'
import { fetchfoodCategoryList, feachacheList } from '@/api/food'

interface Category {
  id: number | null
  name: string
}
interface FoodSku {
  id: number
  price: number
  unit?: string
  num?: number
  images: any[]
}
interface Food {
  id: number
  name: string
  sub_name?: string
  skuList?: FoodSku[]
  num?: number
  images?: Array<{
    file: {
      preview_url: string
    }
  }>
}

const emit = defineEmits<{
  (e: 'selectFood', food: Food): void
  (e: 'back'): void
  (e: 'action', type: string): void
  (e: 'selectCookBookFoods', foods: any[]): void
}>()

const pageQuery = ref({
  page: 1,
  limit: 999999,
  category_id: null as number | null,
  keywords: null as string | null
})
const oneCategories = ref<Category[]>([])
const twoCategories = ref<Category[]>([])
const foods = ref<Food[]>([]) // 原始数据
const filteredFoods = ref<Food[]>([]) // 筛选后的数据
const listLoading = ref(false)
// 当前选中的一级分类，用于加载二级分类
const currentOneCategoryId = ref<number | null>(null)
// 是否已经加载过数据
const hasLoadedData = ref(false)
// 菜谱弹框显示状态
const showCookBookDialog = ref(false)

const loadOneCategories = async () => {
  try {
    const res: any = await fetchfoodCategoryList({
      parent_id: 0,
      page: oneCategoryPage.value,
      limit: 4
    })
    if (res?.status === 200) {
      const data = res.data || {}
      const list = Array.isArray(data.data) ? data.data : []
      oneCategories.value = [{ id: null, name: '全部' }, ...list]
      // 计算一级分类的总页数，驱动翻页按钮可用状态
      if (typeof data.total === 'number' && typeof data.per_page === 'number') {
        foodOneCategoryLastPage.value = Math.max(1, Math.ceil(data.total / data.per_page))
      } else if (typeof data.last_page === 'number') {
        foodOneCategoryLastPage.value = Math.max(1, data.last_page)
      } else {
        // 没有提供总页信息时，根据返回条数与限制粗略判断
        foodOneCategoryLastPage.value =
          list.length < 4 ? oneCategoryPage.value : oneCategoryPage.value + 1
      }
    }
  } catch (e) {
    ElMessage.error('获取一级分类失败')
  }
}

const loadTwoCategories = async (parentId: number | null) => {
  try {
    if (!parentId) {
      twoCategories.value = []
      foodTwoCategoryLastPage.value = 1
      twoCategoryPage.value = 1
      return
    }
    const res: any = await fetchfoodCategoryList({
      parent_id: parentId,
      page: twoCategoryPage.value,
      limit: 5
    })
    if (res?.status === 200) {
      const data = res.data || {}
      twoCategories.value = Array.isArray(data.data) ? data.data : []
      // 根据服务端的分页信息计算总页数
      if (typeof data.total === 'number' && typeof data.per_page === 'number') {
        foodTwoCategoryLastPage.value = Math.max(1, Math.ceil(data.total / data.per_page))
      } else if (typeof data.last_page === 'number') {
        foodTwoCategoryLastPage.value = Math.max(1, data.last_page)
      } else {
        // 如果没有提供总页数信息，保守处理：当返回数量小于限制时视为最后一页
        foodTwoCategoryLastPage.value =
          twoCategories.value.length < 8 ? twoCategoryPage.value : twoCategoryPage.value + 1
      }
    }
  } catch (e) {
    ElMessage.error('获取二级分类失败')
  }
}

const loadFoods = async () => {
  try {
    listLoading.value = true
    const res: any = await feachacheList({
      ...pageQuery.value,
      is_group: 1
    })
    if (res?.status === 200) {
      foods.value = Array.isArray(res.data?.data) ? res.data.data : res.data || []
      hasLoadedData.value = true
      // 初始筛选
      filterFoods()
    }
  } catch (e) {
    ElMessage.error('获取菜品列表失败')
  } finally {
    listLoading.value = false
  }
}

// 自定义筛选函数
const filterFoods = () => {
  if (!hasLoadedData.value) {
    filteredFoods.value = []
    return
  }

  const keywords = pageQuery.value.keywords
  const categoryId = pageQuery.value.category_id

  let result = foods.value

  // 按分类筛选
  if (categoryId !== null) {
    // 这里需要根据实际的分类关系来筛选，暂时保持原逻辑
    // 如果 foods 数据中有 category_id 字段，可以按此筛选
    // result = result.filter(food => food.category_id === categoryId)
  }

  // 按关键词筛选
  if (keywords && keywords.trim()) {
    const searchTerm = keywords.trim().toLowerCase()
    result = result.filter(food => {
      // 按 name 筛选
      const nameMatch = food.name.toLowerCase().includes(searchTerm)

      // 按 sub_name 任意位数匹配筛选
      let subNameMatch = false
      if (food.sub_name) {
        subNameMatch = food.sub_name.toLowerCase().includes(searchTerm)
      }

      return nameMatch || subNameMatch
    })
  }

  filteredFoods.value = result
}

const onSearch = () => {
  if (hasLoadedData.value) {
    // 已有数据，直接筛选
    filterFoods()
  } else {
    // 首次搜索，加载数据
    loadFoods()
  }
}

const onSelectOneCategory = (item: Category) => {
  pageQuery.value.category_id = item.id || null
  currentOneCategoryId.value = item.id || null
  // 清空搜索框
  pageQuery.value.keywords = ''
  // 切换一级分类时，刷新二级分类（重置到第1页）
  twoCategoryPage.value = 1
  loadTwoCategories(currentOneCategoryId.value)
  // 一级分类点击需要刷新菜品列表
  loadFoods()
}

const onSelectTwoCategory = (item: Category) => {
  pageQuery.value.category_id = item.id || null
  // 清空搜索框
  pageQuery.value.keywords = ''
  // 点击二级分类仅查询菜品列表
  loadFoods()
}
const emitSelectFood = (food: Food) => emit('selectFood', food)
const emitBack = () => emit('back')
const emitAction = (type: string) => {
  if (type === 'cookbook') {
    showCookBookDialog.value = true
  } else {
    emit('action', type)
  }
}

// 处理菜谱弹框确认事件
const handleCookBookConfirm = (foods: any[]) => {
  console.log(foods);
  
  emit('selectCookBookFoods', foods)
  showCookBookDialog.value = false
}

// 移除对 category_id 的二级分类自动加载，改为仅在选择一级分类时加载
// 注意：不监听 pageQuery 深度变更以避免重复请求；仅在显式操作时调用 loadFoods

onMounted(async () => {
  await loadOneCategories()
  await loadFoods()
})

// 分页状态与方法（对齐旧项目）
const foodOneCategoryLastPage = ref(1)
const foodTwoCategoryLastPage = ref(1)
const oneCategoryPage = ref(1)
const twoCategoryPage = ref(1)

// 服务端分页：二级分类不再做前端切片

const oneCatePreviousPage = async () => {
  if (oneCategoryPage.value === 1) return
  oneCategoryPage.value -= 1
  // 分页时清空搜索框
  pageQuery.value.keywords = ''
  await loadOneCategories()
}

const oneCateNextPage = async () => {
  if (oneCategoryPage.value >= foodOneCategoryLastPage.value) return
  oneCategoryPage.value += 1
  // 分页时清空搜索框
  pageQuery.value.keywords = ''
  await loadOneCategories()
}

const twoCatePreviousPage = async () => {
  if (twoCategoryPage.value === 1) return
  twoCategoryPage.value -= 1
  // 分页时清空搜索框
  pageQuery.value.keywords = ''
  await loadTwoCategories(currentOneCategoryId.value)
}

const twoCateNextPage = async () => {
  if (twoCategoryPage.value >= foodTwoCategoryLastPage.value) return
  twoCategoryPage.value += 1
  // 分页时清空搜索框
  pageQuery.value.keywords = ''
  await loadTwoCategories(currentOneCategoryId.value)
}
</script>

<style scoped lang="scss">
.desktop-content {
  box-sizing: border-box;
  min-width: 976px;
  height: 986px;
  background: #ffffff;
  border-radius: 20px;
  position: relative;
}
.desktop-column-box {
  background: #ffffff;
  border-radius: 20px 20px 0 0;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.04);
  padding: 20px 30px;
}
.pagingAndSearch-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.paging-list-box {
  position: relative;
  box-sizing: border-box;
  width: 700px;
  overflow: hidden;
  height: 48px;
  background: #ffffff;
  border: 1px solid #d0d0d0;
  border-radius: 25px;
  display: flex;
  align-items: center;
}
.paging-list-item {
  display: inline-block;
  padding: 0 24px;
  height: 48px;
  line-height: 48px;
  font-size: 16px;
  color: #333;
  cursor: pointer;
}
.paging-list-btn {
  position: absolute;
  top: 12px;
  right: 16px;
  display: flex;
  align-items: center;
}
.paging-list-btn .left-btn,
.paging-list-btn .right-btn {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  cursor: pointer;
}
.paging-list-btn .left-btn {
  margin-right: 20px;
}
.paging-list-item .name {
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.paging-list-item-active {
  color: #fff;
  background: #7c0a03;
  border-radius: 24px;
  .name {
    color: #fff !important;
  }
}
.search-box {
  display: flex;
  align-items: center;
  width: 192px;
  height: 48px;
  background: #d2d2d2;
  border-radius: 24px;
  box-sizing: border-box;
}
.search-box .content1 {
  display: flex;
  align-items: center;
  padding-left: 22px;
}
.search-box .content1 > img {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  margin-right: 20px;
}
.search-box .content1 > input {
  font-size: 16px;
  color: #333;
  border: none;
  outline: none;
  background: transparent;
}
.tag-select-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
}
.tag-btn-list {
  display: flex;
  align-items: center;
  max-width: 700px;
  overflow: hidden;
}
.tag-paging-list-btn {
  display: flex;
  align-items: center;
}
.tag-paging-list-btn .left-btn,
.tag-paging-list-btn .right-btn {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  cursor: pointer;
}
.tag-paging-list-btn .left-btn {
  margin-right: 20px;
}
.tag-btn-item {
  min-width: 116px;
  height: 40px;
  line-height: 40px;
  border: 1px solid #d2d2d2;
  border-radius: 12px;
  font-size: 16px;
  text-align: center;
  color: #666;
  cursor: pointer;
  margin-right: 24px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
.tag-btn-item-active {
  border-color: #7c0a03 !important;
  color: #7c0a03 !important;
}
.desktop-scroll-list {
  padding: 0 24px 24px;
  height: 800px;
  box-sizing: border-box;
  overflow-y: auto;
}
.desktop-scroll-list-two {
  padding: 0 24px 24px;
  height: 690px;
  box-sizing: border-box;
  overflow-y: auto;
}
.scroll-list-item-content {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  align-items: center;
  flex-wrap: wrap;
  gap: 5px;
  //   justify-content: space-between;
}
.scroll-list-item {
  position: relative;
  display: flex;
  align-items: flex-start;
  width: 300px;
  height: 130px;
  background: #f4f4f4;
  border-radius: 12px;
  box-sizing: border-box;
  margin-top: 20px;
  cursor: pointer;
}
.image {
  flex-shrink: 0;
  width: 173px;
  height: 130px;
  border-radius: 12px 0 0 12px;
  margin-right: 10px;
}
.not-good-image {
  width: 173px;
  height: 130px;
  border-radius: 12px 0 0 12px;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.not-good-image .image {
  flex-shrink: 0;
  width: 124px;
  height: 124px;
}
.desc-box {
  padding-top: 12px;
  .name {
    width: 90px;
  }
}
.name {
  //   width: 90px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-size: 18px;
  color: #30314a;
}
.money {
  font-size: 14px;
  color: #333333;
  margin-top: 10px;
}
.vip-money {
  font-size: 14px;
  color: #efc291;
  margin-top: 10px;
}
.count {
  font-size: 14px;
  color: #333333;
  margin-top: 30px;
}
.positon-soldOut-box {
  position: absolute;
  left: 0;
  top: 0;
  width: 300px;
  height: 130px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.positon-soldOut-box .image {
  flex-shrink: 0;
  width: 142px;
  height: 117px;
}
.no-data-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 170px;
  margin-top: 250px;
}
.desktop-actions-btn-box {
  position: absolute;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 976px;
  height: 88px;
  box-sizing: border-box;
  padding: 0 30px;
  background: #ffffff;
  box-shadow: 0 -4px 6px rgba(0, 0, 0, 0.04);
  border-radius: 0 0 20px 20px;
}
.btn-list {
  height: 88px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.btn-item {
  display: inline-block;
  padding: 0 42px;
  height: 48px;
  line-height: 48px;
  background: #ffffff;
  border: 1px solid #333333;
  border-radius: 12px;
  cursor: pointer;
  font-size: 18px;
  color: #333333;
  margin-right: 20px;
}
</style>
